package com.bruip.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bruip.reggie.common.BaseResponse;
import com.bruip.reggie.pojo.Category;
import com.bruip.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;
import java.util.List;

/**
 * @author 王若龙
 * @date 2022-10-06 16:46
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService service;

    /**
     * 添加类别
     *
     * @param category 类别
     * @return {@link BaseResponse}<{@link String}>
     */
    @PostMapping
    public BaseResponse<String> addCategory(@RequestBody Category category) {
        service.save(category);
        return BaseResponse.success("添加成功");
    }

    /**
     * 分类页面
     *
     * @param page     页面
     * @param pageSize 显示数量
     * @return {@link BaseResponse}<{@link Page}>
     */
    @GetMapping("/page")
    public BaseResponse<Page> categoryPage(int page, int pageSize) {
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort);
        //查询
        service.page(pageInfo, queryWrapper);

        return BaseResponse.success(pageInfo);
    }

    /**
     * 删除类别
     * TODO 删除前校验是否关联菜品
     * @param ids id
     * @return {@link BaseResponse}<{@link String}>
     */
    @DeleteMapping
    public BaseResponse<String> deleteCategory(Long ids){
        service.removeCategoryById(ids);
        return BaseResponse.success("删除成功");
    }

    /**
     * 更新类别
     *
     * @param category 类别
     * @return {@link BaseResponse}<{@link String}>
     */
    @PutMapping
    public BaseResponse<String> updateCategory(@RequestBody Category category){
        service.updateById(category);
        return BaseResponse.success("修改成功");

    }


    @GetMapping("/list")
    public BaseResponse<List<Category>> listCategoryName(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);

        List<Category> categoryList = service.list(queryWrapper);

        return BaseResponse.success(categoryList);
    }
}
